package com.compass.doctor.ui.consultation

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.compass.doctor.R
import com.compass.doctor.databinding.ActivityConsultationDetailsBinding
import com.compass.doctor.ui.consultation.adapter.ConsultationDoctorAdapter
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.ui.consultation.viewmodel.ConsultationViewModel
import com.compass.doctor.ui.message.util.MeetingOptions
import com.compass.framework.constant.REFRESH_LAUNCH
import com.compass.framework.constant.REFRESH_RX
import com.compass.framework.dialog.CommonMessageDialog
import com.compass.framework.ext.gone
import com.compass.framework.ext.onClick
import com.compass.framework.ext.visible
import com.compass.framework.glide.setUrlCircle
import com.compass.framework.manager.DictionariesManager
import com.compass.framework.manager.UserInfoManager
import com.compass.framework.model.ConsultationOrder
import com.compass.framework.model.Doctor
import com.compass.framework.utils.BigDecimalUtils
import com.compass.framework.utils.DateUtils
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.LogUtil
import com.compass.framework.utils.getDrawableResource
import com.compass.framework.utils.getStringFromResource
import com.netease.yunxin.kit.meeting.sdk.NEJoinMeetingOptions
import com.netease.yunxin.kit.meeting.sdk.NEMeetingChatroomConfig
import com.netease.yunxin.kit.meeting.sdk.NEMeetingError
import com.netease.yunxin.kit.meeting.sdk.NEMeetingIdDisplayOption
import com.netease.yunxin.kit.meeting.sdk.NEMeetingKit
import com.netease.yunxin.kit.meeting.sdk.NEMeetingOptions
import com.netease.yunxin.kit.meeting.sdk.NEWindowMode

/**
 * Description： 会诊详情
 * Date:2023/12/22 9:32
 */
class ConsultationDetailsActivity : BaseVBActivity<ActivityConsultationDetailsBinding>() {

    companion object {
        fun start(context: Context, orderId: String, orderType: Int) {
            val intent = Intent(context, ConsultationDetailsActivity::class.java)
            intent.putExtra("orderId", orderId)
            intent.putExtra("orderType", orderType)
            context.startActivity(intent)
        }
    }

    private var orderType: Int = 1//1-我发起的 2-我参与的
    private val consultationViewModel: ConsultationViewModel by viewModels()
    private lateinit var consultationDoctorAdapter: ConsultationDoctorAdapter
    private var orderId: String = ""
    private var displayName: String = ""



    override fun initView(savedInstanceState: Bundle?) {

        orderId = intent.getStringExtra("orderId")!!
        orderType = intent.getIntExtra("orderType", 1)
        consultationDoctorAdapter = ConsultationDoctorAdapter(2, orderType)
        mBinding.rcyParticipation.apply {
            layoutManager = LinearLayoutManager(this@ConsultationDetailsActivity)
            adapter = consultationDoctorAdapter

        }
        mBinding.tvJoin.onClick {
            joinMeting()
        }
        mBinding.tvOneselfJoin.onClick {
            joinMeting()
        }
        mBinding.tvCancel.onClick {
            //取消会诊
            CommonMessageDialog.Builder(this)
                .setTitle(getStringFromResource(com.compass.framework.R.string.dialog_tips_title))
                .setMessage("是否取消当前会诊？")
                .setConfirm(getStringFromResource(com.compass.framework.R.string.default_confirm))

                .setCancel(getString(com.compass.framework.R.string.default_cancel))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {
                    consultationViewModel.cancelConsultation(orderId)
                    it?.dismiss()
                }.create().show()
        }
        //同意
        mBinding.tvAccept.onClick {

            CommonMessageDialog.Builder(this)
                .setTitle(getStringFromResource(com.compass.framework.R.string.dialog_tips_title))
                .setMessage("是否同意参加会诊？")
                .setConfirm(getStringFromResource(com.compass.framework.R.string.default_confirm))

                .setCancel(getString(com.compass.framework.R.string.default_cancel))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {
                    consultationViewModel.refuseOrAccept(orderId, 1)
                    it?.dismiss()
                }.create().show()

        }
        //拒绝
        mBinding.tvRefuse.onClick {
            CommonMessageDialog.Builder(this)
                .setTitle(getStringFromResource(com.compass.framework.R.string.dialog_tips_title))
                .setMessage("是否拒绝加入会诊？")
                .setConfirm(getStringFromResource(com.compass.framework.R.string.default_confirm))

                .setCancel(getString(com.compass.framework.R.string.default_cancel))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {
                    consultationViewModel.refuseOrAccept(orderId, 0)
                    it?.dismiss()
                }.create().show()


        }
        mBinding.tvFinish.onClick {
            mBinding.edtSummary.text?.let {
                val report = it.toString().trim()
                //结束会诊
                endConsultation(report)
            } ?: kotlin.run {
                showToast("请输入会诊小结")
            }

        }
        //查看记录
        mBinding.tvViewRecord.onClick {
            showToast("暂不支持")
        }

    }

    private fun joinMeting() {
        CommonMessageDialog.Builder(this)
            .setTitle(getStringFromResource(com.compass.framework.R.string.dialog_tips_title))
            .setMessage("是否立即进入会诊？")
            .setConfirm(getStringFromResource(com.compass.framework.R.string.default_confirm))

            .setCancel(getString(com.compass.framework.R.string.default_cancel))
            .setonCancelListener {
                it?.dismiss()
            }
            .setonConfirmListener {
                consultationViewModel.getConsultationPassword(orderId)
                it?.dismiss()
            }.create().show()
    }

    private fun getMyDoctorStatus(doctors: MutableList<Doctor>):Int{
        for (item in doctors){
            if (item.doctorId==UserInfoManager.getUserInfo()?.id){
               return item.status
            }
        }
        return 10086
    }

    override fun initData() {
        consultationViewModel.getConsultationDetails(orderId)
        consultationViewModel.consultationDetailsLiveData.observe(this) {
            it?.let { order ->
                setButton(order.status,getMyDoctorStatus(order.doctors),order.report)
                setPatientInfo(order)
                setInviteDoctorInfo(order.creator)
                consultationDoctorAdapter.setData(order.doctors)

            }
        }

        consultationViewModel.passwordLiveData.observe(this) {
            it?.let {
                loginMeeting(it.meetingNum, displayName, it.password)
            }
        }
        consultationViewModel.refuseOrAcceptData.observe(this) {
            if (it){
                consultationViewModel.getConsultationDetails(orderId)
                LiveDataBus.get().with(REFRESH_LAUNCH).postValue(REFRESH_LAUNCH)
            }

        }
    }

    /**
     * 设置底部按钮状态
     * status -1 已取消 0待支付 1待开始 2进行中 3已结束 4待加入
     * orderType: 1-我发起的 2-我参与的
     */
    private fun setButton(status: Int,myDoctorStatus:Int,report:String?) {
        when (status) {
            0,1 -> {
                if (orderType == 1) {
                    mBinding.clyButton.visible()
                    mBinding.tvCancel.visible()
                    mBinding.tvFinish.gone()
                    mBinding.llJoinOrRefuse.gone()
                } else {
                    mBinding.clyButton.gone()
                }
            }

            2 -> {
                mBinding.clyButton.visible()
                if (orderType == 1) {
                    mBinding.tvCancel.gone()
                    mBinding.llJoinOrRefuse.gone()
                    mBinding.tvJoin.gone()
                    mBinding.llJoinOrFinish.visible()
                    mBinding.clayReport.visible()//展示小结
                } else {
                    mBinding.tvFinish.gone()
                    mBinding.tvCancel.gone()
                    mBinding.llJoinOrRefuse.gone()
                    mBinding.llJoinOrFinish.gone()

                    mBinding.tvJoin.visible()
                }
            }

            3 -> {
                mBinding.clyButton.visible()
                mBinding.clayReport.visible()//展示小结
                mBinding.tvViewRecord.visible()
                mBinding.edtSummary.isFocusable=false
                mBinding.edtSummary.isFocusableInTouchMode=false
                mBinding.edtSummary.setText(getReport(report))

            }

            4 -> {
                mBinding.clyButton.visible()
                if (orderType == 1) {
                    mBinding.tvCancel.visible()
                    mBinding.tvFinish.gone()
                    mBinding.llJoinOrRefuse.gone()
                } else {
                    //判断自己为0显示加入和拒绝  其他不显示
                    if (myDoctorStatus == 0) {
                        mBinding.tvFinish.gone()
                        mBinding.tvCancel.gone()
                        mBinding.llJoinOrRefuse.visible()
                    }else{
                        mBinding.clyButton.gone()
                    }
                }
            }
            else ->{
                mBinding.clyButton.gone()
            }



        }


    }

    private fun getReport(report:String?): String {
        return report ?: kotlin.run {
            "暂未填写"
        }
    }
    private fun endConsultation(report: String) {
        CommonMessageDialog.Builder(this)
            .setTitle(getStringFromResource(com.compass.framework.R.string.dialog_tips_title))
            .setMessage("您确定结束这次会诊吗?")
            .setConfirm(getStringFromResource(com.compass.framework.R.string.default_confirm))

            .setCancel(getString(com.compass.framework.R.string.default_cancel))
            .setonCancelListener {
                it?.dismiss()
            }
            .setonConfirmListener {
                consultationViewModel.finishConsultation(orderId, report)
                it?.dismiss()
            }.create().show()

    }


    /**
     * 设置患者信息
     */
    private fun setPatientInfo(order: ConsultationOrder) {
        mBinding.apply {
            displayName = "${order.patientName}的会诊"
            mBinding.tvTitleBar.setMiddleText(displayName)
            tvName.text = order.patientName
            ivHead.setUrlCircle(order.patientAvatar)
            tvAge.text = order.patientAge
            ivSex.background =
                if (order.patientSex == 1) getDrawableResource(R.mipmap.icon_male) else getDrawableResource(
                    R.mipmap.icon_female
                )
            tvConsultationTime.text = DateUtils.conversionTime(order.dateTime, DateUtils.FORMAT_TWO)
            tvHospitalFee.text =BigDecimalUtils.divide(order.payPrice)
            tvConsultationStatus.text =
                DictionariesManager.getConsultationStatusValue(order.status.toString())
        }
    }

    /**
     * 设置邀请医生信息
     */
    private fun setInviteDoctorInfo(doctor: Doctor?) {
        mBinding.apply {
            ivDoctorHead.setUrlCircle(doctor?.doctorAvatar)
            tvDoctorName.text = doctor?.doctorName
            positionName.text = doctor?.positionName
            tvHospital.text = doctor?.hospitalName
            tvDepartmentName.text = doctor?.departmentName
        }
    }




    /**
     * 登录会议
     */
    private fun loginMeeting(meetingNum: String, displayName: String, password: String) {
        showLoading()
        NEMeetingKit.getInstance()
            //会议账号
            .login(
                UserInfoManager.getMeetingUUID(),
                UserInfoManager.getMeetingToken()
            ) { resultCode, resultMsg, result ->
                LogUtil.e("resultCode$resultCode")
                LogUtil.e("resultMsg$resultMsg")
                LogUtil.e("result$result")
                if (resultCode == NEMeetingError.ERROR_CODE_SUCCESS) {
                    //登录成功
                    joinMeeting(meetingNum, displayName, password)
                } else {
                    showToast("进入会议失败")
                    //登录失败
                    dismissLoading()
                }
            }
    }

    /**
     *加入会议
     */
    private fun joinMeeting(meetingNum: String, displayName: String, password: String) {

        val startMeetingOptions = getMeetingOptions(NEJoinMeetingOptions()) as NEJoinMeetingOptions
        NEMeetingKit.getInstance().meetingService.joinMeeting(
            this,
            MeetingOptions.getJoinMeetingParams(meetingNum, password),
            startMeetingOptions
        ) { resultCode, resultMsg, _ ->
            if (resultCode == NEMeetingError.ERROR_CODE_SUCCESS) {
                //加入成功
                dismissLoading()
                LogUtil.e("joinMeeting==$resultMsg")
            } else {
                dismissLoading()
                showToast(resultMsg)

            }
        }
    }

    private fun getMeetingOptions(options: NEMeetingOptions): NEMeetingOptions {
        options.noVideo = true //入会时关闭视频，默认为 true
        options.noAudio = true //入会时关闭音频，默认为 true
        options.noInvite = false //入会隐藏"邀请"按钮，默认为 false
        options.noChat = false //入会隐藏"聊天"按钮，默认为 false
        options.noWhiteBoard = false //入会隐藏白板入口，默认为 false
        options.noGallery = false //入会隐藏设置"画廊模式"入口，默认为 false
        options.noSwitchCamera = false //入会隐藏"切换摄像头"功能入口，默认为 false
        options.noSwitchAudioMode = false //入会隐藏"切换音频模式"功能入口，默认为 false
        options.noRename = false //入会隐藏"改名"功能入口，默认为 false
        options.showMeetingTime = false //设置入会后是否显示会议持续时间，默认为 false
        options.noMinimize = true //入会是否允许最小化会议页面，默认为 true
        options.defaultWindowMode = NEWindowMode.normal //入会默认会议视图模式
        options.meetingIdDisplayOption =
            NEMeetingIdDisplayOption.DISPLAY_ALL //设置会议中会议 ID 的显示规则，默认为全部显示
        options.noSip = true //会议是否支持 SIP 用户入会，默认为 false
        options.showMeetingRemainingTip = false //会议中是否开启剩余时间（秒）提醒，默认为 false
        options.chatroomConfig = NEMeetingChatroomConfig() //配置聊天室
        options.chatroomConfig.enableFileMessage = true //是否允许发送/接收文件消息，默认为 true
        options.chatroomConfig.enableImageMessage = true //是否允许发送/接收图片消息，默认为 true
        return options
    }
}